<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
        <CommonPage show-footer>
          <div>
              <n-form ref="form"
                :model="searchCondition"
                label-placement="left"
                label-align="right"
                label-width="80px"
                :show-require-mark="false">
                  <div>
                      <div class="grid md:flex md:flex-wrap md:gap-x-1">
                        <n-form-item style="margin-left: 10px;">
                          <label style="width: 70px;">仓库名：</label>
                            <n-select
                                    v-model:value="searchCondition.storeId"
                                    :options="stores"
                                    placeholder="选择类型"
                                    filterable
                            />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                            <label style="width: 70px;">供应商：</label>
                            <n-select
                                    v-model:value="searchCondition.supplierId"
                                    :options="suppliers"
                                    placeholder="选择类型"
                                    filterable
                            />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                          <label style="width: 90px;">采购人员：</label>
                          <n-select
                                  v-model:value="searchCondition.adminId"
                                  :options="admins"
                                  placeholder="选择类型"
                                  filterable
                          />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                            <label style="width: 70px;">商品名：</label>
                            <n-input v-model:value="searchCondition.productName" placeholder="" style="width: 150px"></n-input>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                          <n-button type="primary"  @click="searchByCondition">筛选</n-button>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                          <n-button type="primary" @click="test">添加入库单</n-button>
                        </n-form-item>
                        <n-form-item  style="margin-left: 10px">
                            <n-button type="error" @click="deleteSelectInBoundDocuments">批量删除</n-button>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <n-button type="primary" @click="exportListInfo">导出</n-button>
                        </n-form-item>
                      </div>
                  </div>
              </n-form>
            <AddInboundDocument
                :stores="filteredStores"
                :storeCommodity="filteredStoreCommodity"
                :suppliers="filteredSuppliers"
                :admins="filteredAdmins"
                :option="option"
                @update-page="searchByCondition"
                :show="showForm"
                :onClose="handleClose" />
            <UpdateInboundDocument
                :stores="filteredStores"
                :storeCommodity="filteredStoreCommodity"
                :suppliers="filteredSuppliers"
                :admins="filteredAdmins"
                :option="option"
                :quantityBefore="quantity"
                @update-page="searchByCondition"
                :show1="showForm1"
                :onClose="handleClose"
                :attribute="currentAttribute"
            />
            <n-data-table
                remote
                :single-line="false"
                ref="table"
                :columns="columns"
                :data="storeReceiptList"
                :loading="loading"
                :pagination="paginationReactive"
                :row-key="rowKey"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                @update:checked-row-keys="handleCheck"
            />
          </div>
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import InventoryActions from "@/views/admin/category/components/category-actions.vue";
import AddInboundDocument from "@/views/admin/inventory/components/goods-add.vue"
import UpdateInboundDocument from "../components/goods-add-edit.vue"

const option = ref([])
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const showForm=ref(false);
const showForm1 = ref(false);
const quantity=ref('');
const currentAttribute = ref(null); // 当前编辑的属性
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};
const test = () => {
  showForm.value = true;
};
const searchCondition=ref(
  {
    storeId: -1,
    supplierId: -1,
    adminId: -1,
    productName: '',
    type: 'inbound'
  }
)
const stores = ref([])
stores.value.push({
	label:'全部',
	value:-1,
})
const storeCommodity = ref([])
storeCommodity.value.push({
  label:'全部',
  value:-1,
})
const suppliers = ref([])
suppliers.value.push({
	label:'全部',
	value:-1,
})
const admins = ref([])
admins.value.push({
	label:'全部',
	value:-1,
})

const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 50,
  },
    {
        key: 'id',
        title: '编号',
        width: 50,
    },
    {
        key: 'storeName',
        title: '入库仓库',
        width: 100,

    },
    {
        key: 'storeCommodityName',
        title: '入库货品',
        width: 200,
    },
    {
        key: 'objectName',
        title: '供应商',
        width: 100,

    },
    {
        key: 'price',
        title: '价格',
        width: 80,
    },
    {
        key: 'quantity',
        title: '数量',
        width: 80,
    },
    {
        key: 'adminName',
        title: '采购负责人',
        width: 80,
    },
    {
        key: 'createTime',
        title: '创建时间',
        width: 100,
    },
    {
        key: 'operation',
        title: '操作',
        width: 120,
        render(row) {
            return h(
                InventoryActions,
                {
                    onClickEdit: () => onEditInBoundDocument(row),
                    onClickDelete: () => onDeleteInBoundDocument(row),
                }
            );
        }
    },
]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});

// 过滤掉 '全部' 选项
const filteredStores = computed(() => stores.value.filter(store => store.value !== -1));
const filteredStoreCommodity = computed(() => storeCommodity.value.filter(commodity => commodity.value !== -1));
const filteredSuppliers = computed(() => suppliers.value.filter(supplier => supplier.value !== -1));
const filteredAdmins = computed(() => admins.value.filter(admin => admin.value !== -1));

const storeReceiptList=ref([])
const searchByCondition = async ()=>{
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageStoreReceipt({
      params: {
				...searchCondition.value,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      storeReceiptList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询产品品牌失败！")
  } finally {
    loading.value = false
  }
}
const onDeleteInBoundDocument = async (inBoundDocument) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前入库单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = inBoundDocument
      loading.value = true
      try {
          const res = await api.deleteInBoundDocument({id})
        if(res.code === 200) {
          $message.success("删除入库单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除入库单失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const deleteSelectInBoundDocuments = () => {
  if(checkedRowKeysRef.value.length <= 0) {
    console.log(checkedRowKeysRef.value.length)
    $message.error("当前并未选择入库单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选入库单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteInBoundDocuments({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选入库单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选入库单失败！")
      }finally{
        loading.value = false
      }
    },
  })
}

const onEditInBoundDocument = async (inBoundDocument) => {
  quantity.value = inBoundDocument.quantity;
  console.log(quantity.value);
  currentAttribute.value = inBoundDocument; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}

const queryStoreList = async () => {
	loading.value = true
	try {
		const res = await api.findAllStore()
		if(res.code === 200) {
			res.data.map((item)=>{
				stores.value.push({
					label: item.name,
					value: item.id
				})
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取仓库信息失败！")
	}finally{
		loading.value = false
	}
}
const queryStoreCommodityList = async () => {
	loading.value = true
	try {
		const res = await api.findAllInventory()
		if(res.code === 200) {
			res.data.map((item)=>{
        storeCommodity.value.push({
					label: item.productName,
					value: item.id
				})
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取货物信息失败！")
	}finally{
		loading.value = false
	}
}
const querySupplierList = async () => {
  loading.value = true
  try {
    const res = await api.findAllSupplier()
    if(res.code === 200) {
      res.data.map((item)=>{
        suppliers.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取供应商信息失败！")
  }finally{
    loading.value = false
  }
}
const queryAdminList = async () => {
	loading.value = true
	try {
		const res = await api.findAdminsInboundDocument(
        {
          params: {
            type: searchCondition.value.type,
            role: 'SUPERADMIN'
          }
        }
    )
		if(res.code === 200) {
			res.data.map((item)=>{
				admins.value.push({
					label: item.name,
					value: item.id
				})
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取管理员信息失败！")
	}finally{
		loading.value = false
	}
}
const queryByPage = async ()=>{
    loading.value = true
    try {
        const res = await api.findPageStoreReceipt(
            {
              params: {
								type: searchCondition.value.type,
	              pageNum:paginationReactive.page,
	              pageSize:paginationReactive.pageSize,

              }
            })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            storeReceiptList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: i+1
                }
            })
            $message.success("获取入库单成功！")
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取入库单失败！")
    }finally{
        loading.value = false
    }
}
const exportListInfo = async () => {
  const res = await api.exportStoreReceiptList({
    adminId: searchCondition.value.adminId.toString(),
    storeId: searchCondition.value.storeId.toString(),
    objectId: searchCondition.value.supplierId.toString(),
    productName: searchCondition.value.productName,
    type: searchCondition.value.type,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if (contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else {
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.style.display = 'none'
    const href = window.URL.createObjectURL(blob)
    elink.href = href
    elink.download = fileName
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
	queryStoreList()
	querySupplierList()
  queryStoreCommodityList()
	queryAdminList()
  queryByPage()
})
</script>
<style scoped>
    :deep(.n-data-table-th__title),
    :deep(.n-data-table-td) {
        text-align: center;

    }
    :deep(.n-select) {
        width: 140px !important;
    }

    :deep(.two-line-description) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 控制显示的行数 */
        overflow: hidden;
    }

</style>
